/**
 * 
 */
package com.donghaiair.task;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.donghaiair.business.doc.domain.TDoc;
import com.donghaiair.business.doc.service.ITDocService;
import com.donghaiair.business.empmobileinfo.domain.TEmpMobileinfo;
import com.donghaiair.business.empmobileinfo.service.ITEmpMobileinfoService;
import com.donghaiair.business.push.domain.TPush;
import com.donghaiair.business.push.service.ITPushService;
import com.donghaiair.business.pushmessage.domain.TPushMessage;
import com.donghaiair.business.sms.domain.TDocWorkTaskDetail;
import com.donghaiair.business.sms.service.ITDocWorkTaskDetailService;
import com.donghaiair.business.sms.vo.DocTrankingVo;
import com.donghaiair.business.tasksign.dao.TDocWorkTaskSignMapper;
import com.donghaiair.business.tasksign.domain.TDocWorkTaskSign;
import com.donghaiair.framework.common.util.DateUtil;
import com.donghaiair.framework.common.util.DocTypeUtils;
import com.donghaiair.framework.common.util.EnumConstantResult;
import com.donghaiair.framework.common.util.PushConfigUtil;
import com.donghaiair.framework.common.util.PushUtils;
import com.feilong.core.Validator;

/**
 * @author Cheung
 *
 */
@Component
public class DocTask {

	private static final Logger log = LoggerFactory.getLogger(DocTask.class);
	@Autowired
	private ITDocWorkTaskDetailService taskDetailService;

	@Autowired
	private ITDocService docService;

	@Autowired
	private TDocWorkTaskSignMapper signMapper;

	@Autowired
	private PushUtils pushUtils;

	@Autowired
	private ITPushService pushService;

	@Autowired
	private ITEmpMobileinfoService mobileInfoServcie;

	@Autowired
	private PushConfigUtil config;

	@Scheduled(cron = "0 0 */1 * * ? ")
	public void run() {
		// TODO 公文超时业务 每小时执行一次
		// TODO 超过24小时未批设置为超归状态
		try {
			log.info(DateUtil.getCurrentTimes() + "Task开始执行开始...");
			// 获取近三天待审批的数据
			List<DocTrankingVo> list = taskDetailService.getToPendingDoc();
			if (Validator.isNotNullOrEmpty(list)) {
				for (DocTrankingVo docVo : list) {
					// 当前时间
					Date ThisTime = DateUtil.currentDate();
					// 时间差
					Long timeDifferent = DateUtil.subtractTime(ThisTime, DateUtil.StrToDate(docVo.getTaskTime()));
					// 当时间差大于24*60分钟 并且状态不是超时状态就做修改
					if (timeDifferent > 24 * 60 && !"1".equals(docVo.getIsOverTime())) {
						TDocWorkTaskDetail taskDetail = new TDocWorkTaskDetail();
						taskDetail.setId(docVo.getDetailId());
						taskDetail.setIsOvertime(1);
						taskDetailService.updateById(taskDetail);
						TDocWorkTaskDetail detail = taskDetailService.selectById(docVo.getDetailId());
						if (Validator.isNotNullOrEmpty(detail)) {
							TDoc doc = docService.selectById(detail.getDocId());
							if (Validator.isNotNullOrEmpty(doc)) {
								TDoc tDoc = new TDoc();
								tDoc.setTaskUserName(detail.getTaskUserName());
								tDoc.setReciUserId(detail.getNextUserId());
								tDoc.setTaskDeptName(detail.getTaskDeptName());
								tDoc.setDocTitle(doc.getDocTitle());
								tDoc.setDocTypeCode(doc.getDocTypeCode());
								tDoc.setPushType(EnumConstantResult.PUSH_TYPE_DOC);
								tDoc.setPushTypeCode(EnumConstantResult.PUSH_TYPE_DOC_OVERTIME);
								pushMessage(tDoc);
							}
						}
					}
				}
			}

			// 人员会签定时任务
			List<DocTrankingVo> listSign = signMapper.selectSignOverTime();
			if (Validator.isNotNullOrEmpty(listSign)) {
				for (DocTrankingVo sign : listSign) {
					// 当前时间
					Date ThisTime = DateUtil.currentDate();
					// 时间差
					// timeDifferent = DateUtil.subtractTime(ThisTime,
					// DateUtil.StrToDate(sign.getTaskTime()));
					// 当前时间大于截止时间修改为超时状态
					Date signTime = DateUtil.StrToDate(sign.getTaskTime());
					if (ThisTime.getTime() > signTime.getTime()) {
						TDocWorkTaskSign signs = new TDocWorkTaskSign();
						signs.setIsOverTime(1);
						signs.setId(sign.getId());
						signMapper.updateById(signs);
						TDocWorkTaskSign detail = signMapper.selectById(signs.getId());
						if (Validator.isNotNullOrEmpty(detail)) {
							TDoc doc = docService.selectById(detail.getDocId());
							if (Validator.isNotNullOrEmpty(doc)) {
								TDoc tDoc = new TDoc();
								tDoc.setTaskUserName(detail.getSignUserName());
								tDoc.setReciUserId(detail.getSignUserId());
								tDoc.setTaskDeptName(detail.getSignDeptMajorName());
								tDoc.setDocTitle(doc.getDocTitle());
								tDoc.setDocTypeCode(doc.getDocTypeCode());
								tDoc.setPushType(EnumConstantResult.PUSH_TYPE_DOC);
								tDoc.setPushTypeCode(EnumConstantResult.PUSH_TYPE_DOC_OVERTIME);
								pushMessage(tDoc);
							}
						}
					}

				}
			}
			log.info(DateUtil.getCurrentTimes() + "Task开始执行结束...");
		} catch (Exception e) {
			log.error("定时任务异常!" + e.getMessage());
		}

	}

	public void pushMessage(TDoc doc) {
		if (Validator.isNotNullOrEmpty(doc.getPushType()) && Validator.isNotNullOrEmpty(doc.getPushTypeCode())) {
			// 推送--查询该公文是否可以被推送“”
			TPush push = getPush(doc.getPushType(), doc.getPushTypeCode(), doc.getDocTypeCode());
			if (Validator.isNotNullOrEmpty(push) && Validator.isNotNullOrEmpty(doc)) {

				String empId = doc.getReciUserId();
				if (Validator.isNotNullOrEmpty(empId)) {

					TEmpMobileinfo info = new TEmpMobileinfo();
					info.setEmpId(empId);
					info.setIsPushOfficeOvertime(1);
					// 根据用户id查找到对应的设配号进行推送
					TEmpMobileinfo empMobileinfo = mobileInfoServcie.selectOne(new EntityWrapper<TEmpMobileinfo>(info));
					if (Validator.isNotNullOrEmpty(empMobileinfo)
							&& Validator.isNotNullOrEmpty(empMobileinfo.getDeviceNumber())) {
						// 根据公文类型找到对应的公文code
						String uuId = UUID.randomUUID().toString().replace("-", "");
						Integer code = DocTypeUtils.getCode(doc.getDocTypeCode());
						String content = "{\"docId\":\"" + doc.getId() + "\",\"content\":\"" + doc.getDocTitle()
								+ "\",\"docTypeCode\":\"" + code + "\",\"title\":\"" + doc.getDocTitle()
								+ "\",\"uuid\":\"" + uuId + "\"}";
						String pushTitle = config.getPushMessage();
						pushUtils.pushSingle(pushTitle, doc.getDocTitle(), "", empMobileinfo.getDeviceNumber(),
								JSONObject.toJSON(content).toString());
						TPushMessage tPushMessage = new TPushMessage();
						tPushMessage.setId(UUID.randomUUID().toString().replace("-", ""));
						tPushMessage.setCreateTime(new Date());
						tPushMessage.setCreateUser(doc.getTaskUserName());
						tPushMessage.setEmpId(doc.getReciUserId());
						tPushMessage.setPushTitle(pushTitle);
						tPushMessage.setTypeId(doc.getId());
						tPushMessage.setIsRead(0);
						tPushMessage.setPushContent(doc.getDocTitle());
						tPushMessage.insert();

					}

				}
			}
		}
	}

	/*
	 * private void pushMessageTask(DocTaskRequestBean newDetail) { TDoc tDoc =
	 * new TDoc(); tDoc.setId(newDetail.getDocId()); TDoc doc = null;//
	 * docMapper.selectById(newDetail.getDocId()); if
	 * (Validator.isNotNullOrEmpty(doc)) {
	 * tDoc.setTaskUserName(newDetail.getTaskUserName());
	 * tDoc.setReciUserId(newDetail.getNextUserId());
	 * tDoc.setTaskDeptName(newDetail.getTaskDeptName());
	 * tDoc.setDocTitle(doc.getDocTitle());
	 * tDoc.setDocTypeCode(doc.getDocTypeCode());
	 * tDoc.setPushType(EnumConstantResult.PUSH_TYPE_DOC);
	 * tDoc.setPushTypeCode(EnumConstantResult.PUSH_TYPE_DOC_TOPENDING);
	 * pushMessage(tDoc); } }
	 */
	public TPush getPush(Integer pushType, Integer pushTypeCode, String docTypeCode) {
		TPush push = pushService.selectOne(
				new EntityWrapper<TPush>().where("PUSH_TYPE={0} AND PUSH_TYPE_NAME={1} AND IS_PUSH=1 AND TYPE_CODE={2}",
						pushType, pushTypeCode, docTypeCode));
		return push;

	}
}
